<template>
  <div class="employee-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">员工姓名：</div>

      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="doSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>

    </div>

    <div class="create-container">
      <el-button type="primary" @click="addEmployee">添加员工</el-button>

    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="employeeList">
        <el-table-column type="index" label="序号" />
        <el-table-column label="员工姓名" width="160" prop="name" />
        <el-table-column label="登录账号" width="180" prop="userName" />
        <el-table-column label="联系方式" width="120" prop="phonenumber" />
        <el-table-column label="角色" width="120" prop="roleName" />
        <el-table-column label="状态">
          <template #default="scope">
            <!-- {{ formatStatus(scope.row.status) }} -->
            <el-tag :type="formatInfoType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>

        </el-table-column>

        <el-table-column label="添加时间" prop="createTime" />
        <el-table-column label="操作" fixed="right" width="140">
          <template #default="scope">
            <el-button size="mini" type="text" @click="editEmployee(scope.row.id)">编辑</el-button>

            <el-button size="mini" type="text" @click="delEmployee(scope.row.id)">删除</el-button>

            <el-button size="mini" type="text" @click="resetEmployee(scope.row.id)">重置密码</el-button>

          </template>

        </el-table-column>

      </el-table>

    </div>

    <div class="page-container">
      <el-pagination layout="total, prev, pager, next" :page-size="params.pageSize" :total="total"
        @current-change="pageChange" />
    </div>

    <!-- 添加员工弹窗 -->
    <el-dialog :visible="dialogVisible" @close="closeDialog" title="添加员工" width="480px">
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="80px">
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>

          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="addForm.userName" />
          </el-form-item>

          <el-form-item label="联系方式" prop="phonenumber">
            <el-input v-model="addForm.phonenumber" />
          </el-form-item>

          <el-form-item label="分配角色" prop="roleId">
            <el-select v-model="addForm.roleId" placeholder="请选择角色">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>

          </el-form-item>

          <el-form-item label="员工状态" prop="status">
            <el-radio-group v-model="addForm.status">
              <el-radio :label="0">禁用</el-radio>

              <el-radio :label="1">启用</el-radio>

            </el-radio-group>

          </el-form-item>

        </el-form>

      </div>

      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>

        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>

      </template>

    </el-dialog>
  </div>

</template>

<script>
import {
  getEmployeeListAPI, getRoleListAPI, createEmployeeAPI, delEmployeeAPI,
  editEmployeeAPI, detailEmployeeAPI, resetEmployeeAPI
} from '@/api/employee'

export default {
  name: 'Employee',
  data() {
    return {
      employeeList: [],// 员工列表
      params: {// 员工列表的请求参数
        page: 1,
        pageSize: 10,
        name: '', // 员工姓名
      },
      total: 0,// 员工列表的总条数

      dialogVisible: false, // 控制弹框打开关闭
      roleList: [], // 角色列表
      addForm: {
        name: '',
        phonenumber: '',
        roleId: '',
        status: 1,
        userName: ''
      },
      id: null,// 员工主键，用来判断是否是编辑员工

      addFormRules: {
        name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入登录账号', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请分配角色', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择员工状态', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工列表：按页获取
    async getEmployeeList() {
      const res = await getEmployeeListAPI(this.params)
      this.employeeList = res.data.rows
      this.total = res.data.total
      // console.log('员工列表数据：', this.employeeList)
      console.log('员工初始数据：', res.data)
    },
    //   分页切换
    pageChange(page) {
      this.params.page = page
      // 重新获取员工列表数据
      this.getEmployeeList()
    },
    // 格式化tag类型
    formatInfoType(status) {
      const MAP = {
        0: 'danger',
        1: 'success',
        // 2: 'info',
        // 3: 'danger'
      }
      return MAP[status]
    },

    // 格式化status
    formatStatus(type) {
      const TYPEMAP = {
        0: '禁用',
        1: '启用',
      }
      return TYPEMAP[type]
    },
    // 关闭弹框
    closeDialog() {
      this.dialogVisible = false
      this.id = null//每次关闭id置空，保证只有编辑页面才执行修改员工操作
    },

    // 打开弹框：添加员工
    async addEmployee() {
      // 1. 获取角色列表
      this.addForm = {}// 清空表单记录
      const res = await getRoleListAPI();
      this.roleList = res.data;
      this.dialogVisible = true;
    },

    // 打开弹框：编辑员工
    async editEmployee(id) {
      this.addEmployee()// 打开弹框，渲染角色列表
      //获取员工详细数据，并回显
      const res = await detailEmployeeAPI(id);
      const { name, phonenumber, roleId, status, userName } = res.data;
      this.addForm = { name, phonenumber, roleId, status, userName };
      this.id = id;// id用来判断是编辑员工还是添加员工
      //提交修改放统一放在confirmAdd方法中
      // console.log('编辑员工数据：', this.addForm);
      // console.log('详情员工数据：', res.data);
    },

    // 确认添加员工
    async confirmAdd() {
      // 1. 调用接口
      if (this.id) {
        // 执行编辑提交请求
        await editEmployeeAPI({
          ...this.addForm,
          id: this.id
        })
      } else {
        await createEmployeeAPI(this.addForm)
      }

      // 2. 关闭弹框
      this.dialogVisible = false
      // 3. 重新刷新列表
      this.getEmployeeList()
      // 4. 清空表单记录
    },
    // 删除员工

    delEmployee(id) {
      this.$confirm('删除员工后将不可登录，确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await delEmployeeAPI(id)
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        this.getEmployeeList()
      })
    },

    //重置密码
    resetEmployee(id) {
      this.$confirm('确认重置密码为123456吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await resetEmployeeAPI(id)
        this.$message({
          type: 'success',
          message: '重置成功'
        })
        this.getEmployeeList()
      })

    },

    //查询员工
    doSearch() {
      this.params.page = 1
      // 重置name参数并获取员工列表
      this.getEmployeeList()
    },

  },//这是methods的结尾

  watch: {// 监听搜索框的输入：当输入框从有变为空时，更新为全部列表
    'params.name': {
      handler(newVal) {
        if (newVal === '') {
          this.doSearch()
        }
      },
      immediate: true//立即执行
    }
  },

}
</script>

<style lang="scss" scoped>
.employee-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
